package cn.xingzhe.monster.user.domain.service;

import cn.xingzhe.monster.user.domain.model.UserModel;
import cn.xingzhe.monster.user.domain.repository.UserRepository;
import cn.xingzhe.monster.user.domain.exception.InvalidPasswordException;
import cn.xingzhe.monster.user.domain.exception.UserAlreadyExistsException;
import cn.xingzhe.monster.user.domain.exception.UserNotFoundException;
import cn.xingzhe.monster.user.domain.exception.UserAccountLockedException;
import cn.xingzhe.monster.user.domain.service.PasswordHasher;

/**
 * 用户领域服务
 * 处理用户相关的领域业务逻辑，特别是跨聚合的业务逻辑
 *
 * @author System
 * @version 1.0.0
 * @since 2024-01-01
 */
public class UserDomainService {

    private final UserRepository userRepository;

    public UserDomainService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    /**
     * 验证注册信息
     * 检查邮箱、手机号、用户名是否已存在
     *
     * @param email  邮箱（可为空）
     * @param phone  手机号（可为空）
     * @param username 用户名（可为空）
     */
    public void validateRegistration(String email, String phone, String username) {
        if (email != null && userRepository.existsByEmail(email)) {
            throw UserAlreadyExistsException.emailExists(email);
        }
        if (phone != null && userRepository.existsByPhone(phone)) {
            throw UserAlreadyExistsException.phoneExists(phone);
        }
        if (username != null && userRepository.existsByUsername(username)) {
            throw UserAlreadyExistsException.usernameExists(username);
        }
    }

    /**
     * 验证登录信息
     *
     * @param user 用户模型
     * @param password 密码
     * @param hasher 密码哈希服务
     */
    public void validateLogin(UserModel user, String password, PasswordHasher hasher) {
        if (user == null) {
            throw UserNotFoundException.of("用户不存在");
        }

        // 检查用户是否可以登录
        if (!user.canLogin()) {
            throw UserAccountLockedException.of();
        }

        // 验证密码
        if (!user.verifyPassword(password, hasher)) {
            throw InvalidPasswordException.of();
        }
    }

    /**
     * 验证邮箱登录
     *
     * @param email 邮箱
     */
    public UserModel validateEmailLogin(String email) {
        UserModel user = userRepository.findByEmail(email)
                .orElseThrow(() -> UserNotFoundException.of(email));

        if (!user.canLogin()) {
            throw UserAccountLockedException.of();
        }

        return user;
    }

    /**
     * 验证手机号登录
     *
     * @param phone 手机号
     */
    public UserModel validatePhoneLogin(String phone) {
        UserModel user = userRepository.findByPhone(phone)
                .orElseThrow(() -> UserNotFoundException.of(phone));

        if (!user.canLogin()) {
            throw UserAccountLockedException.of();
        }

        return user;
    }

    /**
     * 检查用户是否可以激活
     *
     * @param userId 用户ID
     * @return 是否可以激活
     */
    public boolean canActivate(String userId) {
        UserModel user = userRepository.findById(userId)
                .orElseThrow(() -> UserNotFoundException.byId(userId));
        return user.canActivate();
    }

    /**
     * 检查用户是否可以锁定
     *
     * @param userId 用户ID
     * @return 是否可以锁定
     */
    public boolean canLock(String userId) {
        UserModel user = userRepository.findById(userId)
                .orElseThrow(() -> UserNotFoundException.byId(userId));
        return user.canLock();
    }
}

